package com.asm.shiroweb.controller;

import com.asm.shiroweb.common.bean.UserBean;
import com.asm.shiroweb.common.lang.Result;
import com.asm.shiroweb.common.util.RedisUtils;
import com.asm.shiroweb.common.util.VerifyCodeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@RestController
@RequestMapping("/common")
public class LoginController {

    private Logger log = LoggerFactory.getLogger(LoginController.class);
/*
    过滤器里 已使用
        factoryBean.setLoginUrl("/index.html"); // 设置登录页面 【是静态页面】【引导未登录(和退出)跳转此页面】
    进行替代
    @GetMapping("/loginIndex")
    public Object loginIndex(){
        return "假装是：登录页面";
    }
*/
    @RequestMapping("getImage")
    public void getImage( HttpServletResponse response) throws IOException{
        // 1. 生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        // 2. 存入redis
        RedisUtils.getInstance().set("code", code, 60);
        // 3. 生成图片 并响应到前端
        ServletOutputStream os = response.getOutputStream();
        response.setContentType("image/png"); // 响应流 为img
        VerifyCodeUtils.outputImage(220, 60, os, code);
        log.info("---------验证码是: {} ----------", code);
    }

    @PostMapping("/login")
    public Object login(UserBean ub){

        // 返回结果
        final HashMap<String, String> errorMsg = new HashMap<>();

/*        // 验证码
        final String redisCode  = (String) RedisUtils.getInstance().get("code");
        log.info("---------redisCode 验证码是: {} ----------", redisCode);

        final String code = ub.getCode();
        log.info("---------code: {} ----------", code);
        if(EmptyUtil.isNullOrEmpty(redisCode) || EmptyUtil.isNullOrEmpty(code) || !redisCode.equalsIgnoreCase(code)){
            errorMsg.put("errorMsg","图片验证码错误！");
            return errorMsg;
        }*/

        // 获取当前正在执行的用户：
        Subject currentUser = SecurityUtils.getSubject();

        currentUser.logout();// 防止权限修改 因为缓存 没反应


        // 让我们登录当前用户，以便检查角色和权限：
        if (!currentUser.isAuthenticated() && !currentUser.isRemembered()) {
//        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(
                    null != ub.getUserName() ? ub.getUserName() : ub.getUserMobile(), ub.getUserPass());

            token.setRememberMe(true);// 指定时间内：不会被其他用户 登录顶替掉

            try {
                currentUser.login(token);
//                currentUser.getSession().setAttribute("currentUser", currentUser.getPrincipal());

                log.info("----登录成功--currentUser.isAuthenticated() = "  + currentUser.isAuthenticated());
                log.info("----登录成功--currentUser.isRemembered() = "  + currentUser.isRemembered());
                return "login Success";

            } catch (UnknownAccountException uae) {
                log.info("----异常---：There is no user with username of " + token.getPrincipal());
                errorMsg.put("errorMsg","用户不存在");

            } catch (IncorrectCredentialsException ice) {
                log.info("----异常---：Password for account " + token.getPrincipal() + " was incorrect!");
                errorMsg.put("errorMsg","账号或密码错误");

            } catch (LockedAccountException lae) {
                log.info("----异常---：The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
                errorMsg.put("errorMsg","账户锁定了");

            }
            // 在这里捕获更多异常（可能是特定于您的应用程序的自定义异常）？
            catch (AuthenticationException ae) {
                //意外情况？错误？
                log.info("登录失败~！{}",ae.getMessage());
                errorMsg.put("errorMsg","登录失败");
            }
        } else {
            errorMsg.put("errorMsg","无需重复登录");
        }

        return errorMsg;
    }

//    @RequiresUser
//    @RequiresAuthentication
    @RequestMapping("/getCurrentUser")
    public Object getCurrentUser(){


//        return "getCurrentUser";
        // 获取当前正在执行的用户：
        Subject currentUser = SecurityUtils.getSubject();
//        final Session session = currentUser.getSession();
//        final Object u = session.getAttribute("currentUser"); session放redis里了 这里会报错

        final Object u = currentUser.getPrincipal();

        log.info("currentUser.isAuthenticated() = "  + currentUser.isAuthenticated());
        log.info("currentUser.isRemembered() = "  + currentUser.isRemembered());
        if (null == u){
            return "还未登录!";
        }else{
            return u;
        }

    }


    @RequestMapping("/unauthorized")
    public Object unauthorized(){


        return "谁都可以访问的页面提示：您没有权限访问哦！";

    }


    @RequestMapping("/needLogin")
    public Result needLogin(){

        return Result.fail("登录已失效，请重新登录");

    }


}
